import { Destroyable, react, reactJson, Event, track, HasOwner, reactJsonWithUndefined } from "earthsdk3";
import { MyProjectManager } from "../MyProjectManager";
import { ES3DTileset, ESImageryLayer, ESTerrainLayer, ESTextLabel } from "earthsdk3";
import { ElMessage } from "element-plus";

export class BaseSceneConfig extends HasOwner<MyProjectManager> {

    _assets: any = [
        {
            type: "地形",
            url: "http://192.168.0.130:9003/terrain/lPi5nXRn/layer.json"
        },
        {
            type: "影像",
            url: "http://0414.gggis.com/maps/vt?lyrs=s&x={x}&y={y}&z={z}"
        },
        {
            type: "瓦片",
            url: "https://www.pipeser.com/cesiumlab/G7qC5vBk/tileset.json"
        },
    ]

    deleteJson(id: string) {
        return {
            text: '删除',
            func: () => {
                return new Promise((resolve) => {
                    this._currentDialog.value = "delete";
                    const d = this._dialogEvent.disposableOnce((res: string) => {
                        d()
                        if (res == "confirm") {
                            this.deleteSceneObject(id);
                            ElMessage({
                                message: '删除成功',
                                type: 'success',
                            })
                        }
                        resolve("ok")
                    });
                })

            }
        }
    }

    //场景树
    private _sceneTreeLists = this.dv(react<any>([]));
    get sceneTreeLists() { return this._sceneTreeLists.value; }
    get sceneTreeListsChanged() { return this._sceneTreeLists.changed; }
    set sceneTreeLists(value: any) { this._sceneTreeLists.value = value; }

    // 显示隐藏弹出框
    private _currentDialog = this.dv(react<string | undefined>(undefined));
    get currentDialog() { return this._currentDialog.value; }
    get currentDialogChanged() { return this._currentDialog.changed; }
    set currentDialog(value: string | undefined) { this._currentDialog.value = value; }

    // 弹出框事件
    private _dialogEvent = this.dv(new Event<[string]>());
    get dialogEvent() { return this._dialogEvent; }

    // 添加场景对象
    addSceneObject(options: any) {
        const { name, url, type, rectangle, maximumLevel, isShowTk, tokenValue } = options;
        let sceneObject: any;
        let newName: string = ""
        if (type == "imagery") {
            sceneObject = this.owner.createSceneObject(ESImageryLayer)
            sceneObject.url = url;
            sceneObject.maximumLevel = maximumLevel;
            newName = name ? name : "未命名影像"
            if (isShowTk) {
                sceneObject.url = `${url}&${isShowTk}=${tokenValue}`
            }
            else {
                sceneObject.url = url
            }
        }
        if (type == "tileset") {
            sceneObject = this.owner.createSceneObject(ES3DTileset)
            sceneObject.url = url;
            newName = name ? name : "未命名瓦片"

        }
        if (type == "terrain") {
            sceneObject = this.owner.createSceneObject(ESTerrainLayer)
            sceneObject.url = url;
            sceneObject.rectangle = [...rectangle]
            newName = name ? name : "未命名地形"

        }


        const item = {
            name: newName,
            id: sceneObject.id,
            type: type,
            show: sceneObject.show,
            contextmenus: [{
                text: '删除',
                func: () => {
                    return new Promise((resolve) => {
                        this._currentDialog.value = "delete";
                        const d = this._dialogEvent.disposableOnce((res: string) => {
                            d()
                            if (res == "confirm") {
                                this.deleteSceneObject(sceneObject.id);
                            }
                            resolve("ok")
                        });
                    })

                }
            }],
            _sceneObject: sceneObject
        }
        this.sceneTreeLists = [...this.sceneTreeLists, item];

        ElMessage({
            message: '添加成功',
            type: 'success',
        })
    }

    // 删除场景对象
    deleteSceneObject(id: string) {
        const index = this.sceneTreeLists.findIndex((item: any) => item.id === id);
        if (index !== -1) {
            const sceneObject = this.sceneTreeLists[index]._sceneObject;
            this.owner.destroySceneObject(sceneObject)
            this.sceneTreeLists.splice(index, 1);
            this.sceneTreeLists = [...this.sceneTreeLists];
        }
    }

    constructor(owner: MyProjectManager) {
        super(owner);

        if (localStorage.getItem("sceneConfig")) {
            const sceneConfig: any = JSON.parse(localStorage.getItem("sceneConfig") as string);
            this.sceneTreeLists = sceneConfig.map((item: any) => {
                return {
                    name: item.name,
                    id: item.id,
                    type: item.type,
                    show: item.show,
                    contextmenus: [this.deleteJson(item.id)],
                    _sceneObject: this.owner.createSceneObjectFromJson(JSON.parse(item.objJsonStr))
                }
            })

        } else {
            // 影像
            const sceneObject = this.owner.createSceneObjectFromJson({
                "id": "9812a65f-0de0-4f7b-b234-809c0c2fb8ef",
                "type": "ESImageryLayer",
                "url": "https://server.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"
            }) as any;
            sceneObject.maximumLevel = 18
            console.log("sceneObject", sceneObject);


            const item = {
                name: "默认影像",
                id: sceneObject.id,
                type: "imagery",
                show: sceneObject.show,
                contextmenus: [this.deleteJson(sceneObject.id)],
                _sceneObject: sceneObject
            }
            this.sceneTreeLists = [item];
        }

        {
            const update = () => {
                if (owner.modelser2Manager.modelser2Url || owner.terrainrtsManager.terrainRtsUrl) return;
                const sceneConfig: any = this.sceneTreeLists.map((item: any) => {
                    return {
                        name: item.name,
                        id: item.id,
                        type: item.type,
                        show: item.show,
                        objJsonStr: JSON.stringify(item._sceneObject.json)
                    }
                })
                localStorage.setItem("sceneConfig", JSON.stringify(sceneConfig))

            }
            this.dispose(this.sceneTreeListsChanged.disposableOn(update))
        }
    }

}















